﻿using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace ScrollingSnaping;

internal class Program
{
    [DllImport("user32.dll")]
    public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, uint dwExtraInfo);
    private const uint MOUSEEVENTF_WHEEL = 0x0800;

    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll", SetLastError = true)]
    static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Press any key to continue.");
        Console.ReadKey();
        var i = 0;
        string outputFolder = Environment.CurrentDirectory+"\\screenshots";
        if (!Directory.Exists(outputFolder))
        {
            Directory.CreateDirectory(outputFolder);
        }
        while (true)
        {
            IntPtr hwnd = GetForegroundWindow();
            if (hwnd == IntPtr.Zero)
            {
                Console.WriteLine("No active window found.");
                continue;
            }

            if (!GetWindowRect(hwnd, out RECT rect))
            {
                Console.WriteLine("Failed to get window rect.");
                continue;
            }

            int width = rect.Right - rect.Left;
            int height = rect.Bottom - rect.Top;

            using var bitmap = new Bitmap(width, height);
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                graphics.CopyFromScreen(rect.Left, rect.Top, 0, 0, new Size(width, height));
            }
            bitmap.Save($"screenshots\\screenshot{i}.png");
            Console.WriteLine($"taked{i}");
            i++;
            mouse_event(MOUSEEVENTF_WHEEL, 0, 0, unchecked((uint)500), 0); // Scroll down
            Task.Delay(1000).Wait();
            Console.WriteLine($"scrolled{i}");
        }
    }
}
